import { RequestHandler } from 'express'
import { failure, success } from '@/utils/response'
import userService from '@/services/userService'
import { blockUser } from '@/utils/tools'

const getUsers: RequestHandler = async (req, res) => {
  try {
    const data = await userService.getUsers(req.query)
    success(res, '查询用户列表成功。', data)
  } catch (error) {
    failure(res, error as Error, '查询用户列表失败：')
  }
}

const signOut: RequestHandler = async function (req, res) {
  try {
    await blockUser(req)
    success(res, '登出成功')
  } catch (error) {
    failure(res, error as Error, '登出失败：')
  }
}

const getCurrentUserInfo: RequestHandler = async function (req, res) {
  try {
    const data = await userService.getUserInfo(req.userId as number)
    success(res, '查询当前用户信息成功', data)
  } catch (error) {
    failure(res, error as Error, '查询当前用户信息失败：')
  }
}

const getUserInfo: RequestHandler = async function (req, res) {
  try {
    const user = await userService.getUserInfo(+req.params.id)
    success(res, '查询用户成功。', user)
  } catch (error) {
    failure(res, error as Error, '查询用户失败：')
  }
}

const updateUserInfo: RequestHandler = async function (req, res) {
  try {
    const data = await userService.updateUserInfo(req.userId as number, req.body)
    success(res, '更新用户信息成功。', data)
  } catch (error) {
    failure(res, error as Error, '更新用户信息失败：')
  }
}

const updateAccount: RequestHandler = async function (req, res) {
  try {
    const data = await userService.updateAccount(req.userId as number, req.body)
    await blockUser(req)
    success(res, '更新账户信息成功，请重新登录', data)
  } catch (error) {
    failure(res, error as Error, '更新账户信息失败：')
  }
}

export default {
  getUsers,
  signOut,
  getCurrentUserInfo,
  getUserInfo,
  updateUserInfo,
  updateAccount,
}
